﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace TemplateLibraryConnector
{
    public partial class Selector : LayoutsPageBase
    {
        private const string FolderGif = "/_layouts/images/folder.gif";
        private TemplateLibraryConnectorSettings _settings;
        private SPList _documentLibrary;
        private string _destination;
        private string _defaultHubAddress;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Uri uri = Request.UrlReferrer;
                if (uri != null)
                {
                    _destination = uri.AbsoluteUri.ToLower().Replace("Forms/AllItems.aspx".ToLower(), "");
                    _documentLibrary = TemplateLibraryConnectorUtility.GetDocumentLibrary(_destination);
                    _defaultHubAddress = TemplateLibraryConnectorUtility.GetSiteUrlFromLibrary(Request.UrlReferrer.OriginalString, _documentLibrary.Title);
                    _settings = TemplateLibraryConnectorSettings.LoadFromList(_documentLibrary);
                    PopulateTree();
                }
                else
                {
                    // Log here
                }
            }
        }

        private void PopulateTree()
        {
            if (_settings == null || _settings.Enabled == false)
            {
                // Missing settings, log this
                return;
            }

            using (var site = new SPSite(_settings.GetTemplateHubAddress(_defaultHubAddress)))
            {
                SPWeb web = site.RootWeb;
                var webNode = new TreeNode(web.Title, "", FolderGif) {Expanded = true, SelectAction = TreeNodeSelectAction.None};
                TreeSourceDocLib.Nodes.Add(webNode);
                AddFolders(webNode);
            }
        }

        private void AddFolders(TreeNode webNode)
        {
            IEnumerable<SPFolder> templateLibraryRootFolders = TemplateLibraryConnectorUtility.GetTemplateLibraryRootFolders(_settings, _defaultHubAddress);

            if (templateLibraryRootFolders != null && templateLibraryRootFolders.Count() > 0)
            {
                foreach (var templateLibraryRootFolder in templateLibraryRootFolders)
                {
                    var libNode = new TreeNode(templateLibraryRootFolder.DocumentLibrary.Title, "", FolderGif)
                                      {Expanded = true, SelectAction = TreeNodeSelectAction.None};
                    webNode.ChildNodes.Add(libNode);

                    AddTemplates(libNode, templateLibraryRootFolder, _destination);
                }
            }
            else
            {
                var libNode = new TreeNode("No template libraries to list. Either none have been selected for this library, or you do not have access to those selected.")
                                  {Expanded = true, SelectAction = TreeNodeSelectAction.None};
                webNode.ChildNodes.Add(libNode);
            }
        }

        /// <summary>
        /// Recursive function to unfold a template document library into a tree structure
        /// </summary>
        private void AddTemplates(TreeNode webNode, SPFolder folder, string targetFolderUrl)
        {
            var spFolders = folder.SubFolders.Cast<SPFolder>().ToList();
            spFolders.Sort((f1, f2) => f1.Name.CompareTo(f2.Name));

            foreach (SPFolder subFolder in spFolders)
            {
                // Only parse real item folders
                if (subFolder.Item == null)
                    continue;

                // Add a sub menu level and recurse into that
                var subNode = new TreeNode(subFolder.Item.Name, "", FolderGif)
                                  {Expanded = true, SelectAction = TreeNodeSelectAction.None};
                webNode.ChildNodes.Add(subNode);
                AddTemplates(subNode, subFolder, targetFolderUrl);
            }

            var spFiles = folder.Files.Cast<SPFile>().ToList();
            // Include only templates the user has access/permissions to open
            var readFiles = spFiles.Where(spFile => spFile.CanOpenFile(true)).ToList();
            readFiles.Sort((f1, f2) => f1.Name.CompareTo(f2.Name));

            // Add all files from the folder
            foreach (SPFile file in readFiles)
            {
                SPListItem fileItem = file.Item;

                if (fileItem == null)
                    continue;

                string navigateUrl = string.Format(
                    @"javascript:createNewDocumentWithProgID('{0}/{1}', '{2}', 'SharePoint.OpenDocuments', false);window.frameElement.commitPopup();",
                    fileItem.ParentList.ParentWeb.Url, fileItem.File.Url, targetFolderUrl);

                var subNode = new TreeNode(string.Format("{0} ({1})", fileItem.File.Name, fileItem.Title), "", "/_layouts/images/NEWDOC.gif")
                                  {
                                      Expanded = true,
                                      NavigateUrl = navigateUrl,
                                      SelectAction = TreeNodeSelectAction.Select,
                                      ToolTip = fileItem.GetValueOrDefault(_settings.DescriptionFieldName, ""),
                                  };
                webNode.ChildNodes.Add(subNode);
            }
        }
    }
}